package router

import (
	"context"
	"errors"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"os"
	"os/signal"
	"smyx.com/gwt/global"
	"smyx.com/gwt/router/v1"
	"syscall"
	"time"
)

type Register func(*gin.Engine)

// RunServer 启动服务
func RunServer() {
	r := initRouter(v1.UserApi, v1.RoleApi)
	srv := &http.Server{
		Addr:    ":" + global.GApp.Config.App.Port,
		Handler: r,
	}
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			global.GApp.Log.Fatal("listen: %s\n", zap.Any("err", err))
		}
	}()
	global.GApp.Log.Info("服务运行中 >>>>>>>>>>>>>>>>>>>> ")
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	global.GApp.Log.Info("开始关闭服务 >>>>>>>>>>>>>>>>>>>> ")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		global.GApp.Log.Fatal("Server Shutdown:", zap.Any("err", err))
	}
	global.GApp.Log.Info("服务已关闭!!!")
}

// 初始化路由
func initRouter(routers ...Register) *gin.Engine {
	rs := append([]Register{}, routers...)
	r := gin.New()
	loadStaticResources(r)
	for _, register := range rs {
		register(r)
	}
	return r
}

// 加载前端项目资源
func loadStaticResources(r *gin.Engine) {
	r.StaticFile("/", "./static/dist/index.html")
	r.Static("/assets", "./static/dist/assets")
	r.StaticFile("/favicon.ico", "./static/dist/favicon.ico")
	r.Static("/public", "./static")
	r.Static("/storage", "./storage/app/public")
}
